DAMN = (typeof DAMN != "undefined")?  DAMN : {};

DAMN.LoginMananger = new function() 
{ 

  this.init = function() {
    this.userid = 0;

    $(document).ajaxError(function(event, request, settings){
      DAMN.Log.page("Error requesting page " + settings.url +" ("+request.status+")", request.responseText);
      
      DAMN.LoginMananger.Dispath(request.status);
    });
    
    var self = this;
    
    $("#dialog-login").dialog({
  		autoOpen: false,
  		height: 'auto',
  		width: 350,
  		modal: true,
  		buttons: {
  			'Login': function() {
  			   var diag = $(this);
  			   $.post("/accounts/login/?next=/", $("#login-form").serializeArray(), function(data, textStatus, XMLHttpRequest) {
              DAMN.Log.debug("dialog-login: "+data+', '+textStatus+', '+XMLHttpRequest);
              if (textStatus=='success') {
                diag.dialog('close');
                self.Refresh();
              }
            });
  			},
  			Cancel: function() {
  				$(this).dialog('close');
  			}
  		},
  		close: function() {
  		}
  	});  	

		$("#dialog-message").dialog({
		  autoOpen: false,
			modal: true,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
	
	};
	
	this.AttachTo = function(parent) {
	this.parent = parent;
    //parent.tabs('add', '#tabs-User', "User");
    //this.tab = $("#tabs-User");
    this.tab = $('<li id="tabs-User" class="user-tab ui-state-default ui-corner-top"><a href="#tabs-User">Not set</a></li>');
    this.content = $('<div id="tabs-User" class="ui-tabs-panel ui-widget-content ui-corner-bottom"></div>');
    parent.children('ul').first().append(this.tab);
    parent.append(this.content);
    
    this.content.addClass('ui-tabs-hide');
    
    var self = this;
    this.tab.click(function() {
      self.ShowTab();
    });
    
    
    $('li a[href$="tabs-User"]:parent').parent().css({'position': 'absolute', 'top':'6px', 'right':'5px'});
    
    self.Refresh();
    
    
    $('.login').live('click', function() {
      $("#dialog-login-content").load("/accounts/login/");
      $('#dialog-login').dialog('open');
      return false;
		});
		
		$('.logout').live('click', function() {
      $.get("/accounts/login/logout/", function(data, textStatus, XMLHttpRequest) {
        DAMN.Log.debug("LOGOUT: "+data+', '+textStatus+', '+XMLHttpRequest);
        self.Refresh();
      });
      return false;
		});
	};
	
	this.ShowTab = function()
	{
	  this.parent.children('.ui-widget-content').addClass('ui-tabs-hide');
      this.parent.children('ul').children('.ui-tabs-selected').removeClass('ui-tabs-selected');
      this.parent.children('ul').children('.ui-state-active').removeClass('ui-state-active');
      this.Refresh();
	  this.content.removeClass('ui-tabs-hide');
      this.tab.addClass('ui-tabs-selected ui-state-active');
  };
  
  this.HideTab = function()
	{
	  this.content.addClass('ui-tabs-hide');
    this.tab.removeClass('ui-tabs-selected ui-state-active');
  };
	
	this.Refresh = function()
  {
    var self = this;
    self.content.load("/user/", function() {
      // Set the user name on the tab.
      self.username = $("#username").text();
      $('li a[href$="tabs-User"]').text(self.username);

      // if userid is undefined we aren't loggedin.
      if ($("#userid").length) {
        self.userid = $("#userid").text();
      } else {
        self.userid = 0;
      }

    });
  };
  
  this.LoggedIn = function(error) {
    return self.userid != 0;
  };
  
  this.Dispath = function(error)
  {
    if (error == 401) { //401 unauthorized
      $("#dialog-login-content").load("/accounts/login/");
  		$('#dialog-login').dialog('open');
    }
    else if (error == 403) { //403 forbidden
      $('#dialog-message').dialog('open');
    }
    else
      DAMN.Log.error("DAMN.LoginMananger: unhandled error code: "+error);
  };		
};
